package com.xsprite.managesys.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xsprite.managesys.bean.QueryServer;
import com.xsprite.managesys.service.ServersDatabaseManager;

/**
 * Servlet implementation class QueryEverydayLoginServlet
 */
public class QueryEverydayLoginServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private final int DAY = 7;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		try{
			com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(queryParam("paras"));
			if (checkParas(jsonObj)) {
				List<QueryServer> servers = getServers(jsonObj);
				ServersDatabaseManager.getInstance().writeEverydayLoginToDisk(this.getServletContext().getRealPath("/registPlayers"), servers, DAY);
			}
		} catch (Exception ex){
			getResp().getWriter().print(ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	private List<QueryServer> getServers(JSONObject jsonObject){
		List<QueryServer> result = new ArrayList<QueryServer>();
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		for(int i = 0; i < serversArray.size(); i++){
			JSONObject serverObj = (JSONObject) serversArray.get(i);
			QueryServer server = ServersDatabaseManager.getInstance().getServerById(Integer.parseInt(serverObj.getString("tag").split("_")[0]));
			result.add(server);
		}
		return result;
	}
	
	private boolean checkParas(JSONObject jsonObject) throws IOException {
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		if (serversArray.size() < 1) {
			getResp().getWriter().print("服务器不能为空");
			return false;
		}
		return true;
	}
}
